package cn.cxl.utils;

import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import static android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;

public class StringUtil {
    /**
     * 字符串是否为空
     */
    public static boolean isEmpty(String txt) {
        return txt == null || txt.equals("");
    }

    public static String setIsEmpty(String txt) {
        return setIsEmptyResult(txt, "-");

    }

    public static String setIsEmpty2(String txt) {
        return setIsEmptyResult(txt, "无");
    }

    public static String setIsEmptyResult(String txt, String result) {
        return isEmpty(txt) ? result : txt;
    }

    /**
     * @param from
     * @return
     */
    public static List<String> convert(String[] from) {
        ArrayList<String> list = new ArrayList<String>();
        for (String strings : from) {
            list.add(strings);
        }
        return list;
    }

    /**
     * inputStream 转换成 String
     *
     * @param is
     * @return
     * @throws IOException
     */
    public static String inputStream2String(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = -1;
        while ((i = is.read()) != -1) {
            baos.write(i);
        }
        return baos.toString();
    }

    /**
     * 获得日期时间String
     *
     * @param typeid 0：日期和时间 1：日期 2：时间 3:日期时间没有秒
     * @return String
     */
    public static String getDate(Date date, int typeid) {
        if (date == null)
            date = new Date(System.currentTimeMillis());
        switch (typeid) {
            case 0:
                SimpleDateFormat dateFormat = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss");
                return dateFormat.format(date);
            case 1:
                dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                return dateFormat.format(date);
            case 2:
                dateFormat = new SimpleDateFormat("HH:mm:ss");
                return dateFormat.format(date);
            case 3:
                dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                return dateFormat.format(date);
            case 4:
                dateFormat = new SimpleDateFormat("HH:mm");
                return dateFormat.format(date);
            case 5:
                dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                return dateFormat.format(date);
            default:
                return "";
        }
    }

    public static String getTime(int flag, Date date) {
        SimpleDateFormat format = null;
        switch (flag) {
            case 1:
                format = new SimpleDateFormat("yyyy-MM-dd");
                break;
            case 2:
                format = new SimpleDateFormat("yyyy");
                break;
            case 3:
                format = new SimpleDateFormat("MM");
                break;
            case 4:
                format = new SimpleDateFormat("dd");
                break;
        }
        return format.format(date);
    }

    public static String getTime(Date date) {
        SimpleDateFormat format = null;
        format = new SimpleDateFormat("yyyy年MM月dd日");


        return format.format(date);
    }

    public static String getNewTime(int flag) {
        SimpleDateFormat format = null;
        switch (flag) {
            case 1:
                format = new SimpleDateFormat("yyyy-MM-dd");
                break;
            case 2:
                format = new SimpleDateFormat("yyyy");
                break;
            case 3:
                format = new SimpleDateFormat("MM");
                break;
            case 4:
                format = new SimpleDateFormat("dd");
                break;
        }
        return format.format(System.currentTimeMillis());
    }

    public static String getNewTime1(int flag) {
        SimpleDateFormat format = null;
        switch (flag) {
            case 1:
                format = new SimpleDateFormat("yyyy-MM-dd");
                break;
            case 2:
                format = new SimpleDateFormat("yyyy");
                break;
            case 3:
                format = new SimpleDateFormat("MM");
                break;
            case 4:
                format = new SimpleDateFormat("dd");
                break;
        }
        return format.format((System.currentTimeMillis() - 604800000));
    }

    /**
     * 获得日期时间
     *
     *  typeid 0：日期和时间 1：日期 2：时间 3:日期时间没有秒
     * @return Date
     */
    public static Date getDateById(String date, int typeid) {
        try {
            switch (typeid) {
                case 0:
                    SimpleDateFormat dateFormat = new SimpleDateFormat(
                            "yyyy-MM-dd HH:mm:ss");
                    return dateFormat.parse(date);
                case 1:
                    dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    return dateFormat.parse(date);
                case 2:
                    dateFormat = new SimpleDateFormat("HH:mm:ss");
                    return dateFormat.parse(date);
                case 3:
                    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    return dateFormat.parse(date);
                case 4:
                    dateFormat = new SimpleDateFormat("HH:mm");
                    return dateFormat.parse(date);
                default:
                    return new Date();
            }
        } catch (ParseException e) {
            return new Date();
        }
    }

    // 清除html标签
    public static String delHTMLTag(String txt) {
        if (txt == null || txt.equals(""))
            return "";
        return txt.replaceAll("<(.|\n)*?>", "").replaceAll("&(.)*?;", "")
                .trim();
    }

    // 限制字符串长度
    public static String limitLength(String txt, int maxLength) {
        if (txt == null || txt.equals(""))
            return "";
        return txt.trim()
                .substring(0, Math.min(txt.trim().length(), maxLength));
    }

    // 限制字符串长度
    public static String null2String(String txt) {
        return (txt == null) ? "" : txt;
    }

    // 中文转换成地址格式
    public static String getUrlText(String txt, Boolean flag) {
        if (txt == null || txt.equals(""))
            return "";
        if (flag) {
            return java.net.URLEncoder.encode(txt.trim());
        } else {
            return txt;
        }
    }

    // 地址格式转换成中文
    public static String getTextFromUrl(String txt) {
        if (txt == null || txt.equals(""))
            return "";
        return java.net.URLDecoder.decode(txt.trim());
    }

    /**
     * BASE64解密
     *
     * @param key
     * @return
     * @throws Exception
     */
    // public static byte[] decryptBASE64(String key) throws Exception {
    // return Base64.decode(key);
    // }

    /**
     * BASE64加密
     *
     * @param key
     * @return
     * @throws Exception
     */
    // public static String encryptBASE64(byte[] key) throws Exception {
    // return Base64.encode(key);
    // }

    /**
     * MD5加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] encryptMD5(byte[] data) throws Exception {

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(data);

        return md5.digest();

    }

    /*
     * private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5',
     * '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'FeedbackActivity' };
     *
     * public static String toHexString(byte[] b) { //String to byte
     * StringBuilder sb = new StringBuilder(b.length * 2); for (int i = 0; i <
     * b.length; i++) { sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
     * sb.append(HEX_DIGITS[b[i] & 0x0f]); } return sb.toString(); }
     */

    public static String getMD5Str(String s) {
        try {
            // Create MD5 Hash
            MessageDigest digest = MessageDigest
                    .getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            StringBuffer md5StrBuff = new StringBuffer();

            for (int i = 0; i < messageDigest.length; i++) {
                if (Integer.toHexString(0xFF & messageDigest[i]).length() == 1)
                    md5StrBuff.append("0").append(
                            Integer.toHexString(0xFF & messageDigest[i]));
                else
                    md5StrBuff.append(Integer
                            .toHexString(0xFF & messageDigest[i]));
            }
            return md5StrBuff.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * SHA加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] encryptSHA(byte[] data) throws Exception {

        MessageDigest sha = MessageDigest.getInstance("SHA");
        sha.update(data);

        return sha.digest();
    }

    /**
     * 计算两个日期型的时间相差多少时间
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return
     */
    public static String twoDateDistance(Date startDate, Date endDate) {

        if (startDate == null || endDate == null) {
            return null;
        }
        long timeLong = endDate.getTime() - startDate.getTime();
        if (timeLong < 60 * 1000)
            return timeLong / 1000 + "秒";
        else if (timeLong < 60 * 60 * 1000) {
            timeLong = timeLong / 1000 / 60;
            return timeLong + "分";
        } else if (timeLong < 60 * 60 * 24 * 1000) {
            timeLong = timeLong / 60 / 60 / 1000;
            return timeLong + "时";
        } else if (timeLong < 60 * 60 * 24 * 1000 * 7) {
            timeLong = timeLong / 1000 / 60 / 60 / 24;
            return timeLong + "天";
        } else if (timeLong < 60 * 60 * 24 * 1000 * 7 * 4) {
            timeLong = timeLong / 1000 / 60 / 60 / 24 / 7;
            return timeLong + "周";
        } else {
            // SimpleDateFormat sdf = new
            // SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
            timeLong = timeLong / 1000 / 60 / 60 / 24 / 7 / 4;
            return timeLong + "月";
            // return sdf.format(endDate);
        }
    }

    public static String getStandardDate(String timeStr) {

        StringBuffer sb = new StringBuffer();

        long t = Long.parseLong(timeStr);
        long time = System.currentTimeMillis() - (t * 1000);
        long mill = (long) Math.ceil(time / 1000);//秒前

        long minute = (long) Math.ceil(time / 60 / 1000.0f);// 分钟前

        long hour = (long) Math.ceil(time / 60 / 60 / 1000.0f);// 小时

        long day = (long) Math.ceil(time / 24 / 60 / 60 / 1000.0f);// 天前

        if (day - 1 > 0) {
            sb.append(day + "天");
        } else if (hour - 1 > 0) {
            if (hour >= 24) {
                sb.append("昨天");
            } else {
                sb.append(hour + "小时");
            }
        } else if (minute - 1 > 0) {
            if (minute == 60) {
                sb.append("1小时");
            } else {
                sb.append(minute + "分钟");
            }
        } else if (mill - 1 > 0) {
            if (mill == 60) {
                sb.append("1分钟");
            } else {
                sb.append(mill + "秒");
            }
        } else {
            sb.append("刚刚");
        }
        if (!sb.toString().equals("刚刚")) {
            if (!sb.toString().equals("昨天"))
                sb.append("前");
        }
        return sb.toString();
    }

    public static String getStandardDate1(String timeStr) {

        String text;

//系统时间
        String dare = getDate(null, 1);

        int i = Integer.parseInt(String.valueOf(timeStr));
//得到时间
        String dare1 = getDate(new Date(i * 1000L), 1);
        String[] spStrurl = dare1.split("-");
        if (dare.equals(dare1)) {
            text = "<h1>今天</h1>";


        } else if (dare.equals(spStrurl[0] + "-" + spStrurl[1] + "-" + (Integer.valueOf(spStrurl[2]) + 1))) {
            text = "<h1>昨天</h1>";

        } else {
            text = "<big>" + spStrurl[2] + "</big><small>  " + spStrurl[1] + "月" + "</small>";

        }


        String html2 = "<font color= '#FF0000'>"
                + "￥" + "<big>" + "示例文字"
                + "</big></font> "
                + "起" + "<big>" + "示例文字"
                + "</small>";
        String html = "<html>" +
                "<head><title>TextView使用HTML</title></head>" +
                "<body><p><strong>强调</strong></p><p><em>斜体</em></p>"
                + "<p><a href=\"http://www.dreamdu.com/xhtml/\">超链接HTML入门</a>学习HTML!</p><p><font color=\"#aabb00\">颜色1"
                + "</p><p><font color=\"#00bbaa\">颜色2</p><h1>标题1</h1><h3>标题2</h3><h6>标题3</h6><p>大于>小于<</p><p>" +
                "下面是网络图片</p><img src=\"http://avatar.csdn.net/0/3/8/2_zhang957411207.jpg\"/></body>" +
                "</html>";
        return text;
    }

    public static String getDateDistance(String date) {

        if (date == null || date.equals("")) {
            return "";
        }
        long timeLong = System.currentTimeMillis() / 1000
                - Long.parseLong(date);
        System.out.println("  currentTimeMillis   "
                + System.currentTimeMillis() / 1000);
        System.out.println("  date   " + Long.parseLong(date));
        if (timeLong < 60)
            return timeLong + "秒前";
        else if (timeLong < 60 * 60) {
            timeLong = timeLong / 60;
            return timeLong + "分钟前";
        } else if (timeLong < 60 * 60 * 24) {
            timeLong = timeLong / 60 / 60;
            return timeLong + "小时前";
        } else if (timeLong < 60 * 60 * 24 * 7) {
            timeLong = timeLong / 60 / 60 / 24;
            return timeLong + "天前";
        } else if (timeLong < 60 * 60 * 24 * 1000 * 7 * 4) {
            timeLong = timeLong / 1000 / 60 / 60 / 24 / 7;
            return timeLong + "周";
        }
//		 else {
//		 //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		 //sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
//		 timeLong = timeLong / 1000 / 60 / 60 / 24 / 7 / 4;
//		 return timeLong + "月";
//		 //return sdf.format(endDate);
//		 }
        else {
            return getDate(Integer.parseInt(date));
        }
    }

    public static String getFileNameFromUrl(String url) {
        try {
            return url.substring(url.lastIndexOf("/"), url.length());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getDate(int date_s) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date(date_s * 1000L));
        return date;
    }

    public static String getDateMinute(int date_s) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date = sdf.format(new Date(date_s * 1000L));
        return date;
    }

    public static String getDateMinute(long date_s) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date = sdf.format(new Date(date_s));
        return date;
    }

    public static String getDateMinutes(int date_s) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date(date_s * 1000L));
        return date;
    }

    public static String times(int time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy.MM.dd");
        @SuppressWarnings("unused")
        long lcc = Long.valueOf(time);
        int i = Integer.parseInt(String.valueOf(time));
        String times = sdr.format(new Date(i * 1000L));
        return times;

    }

    public static String times1(int time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd");
        @SuppressWarnings("unused")
        long lcc = Long.valueOf(time);
        int i = Integer.parseInt(String.valueOf(time));
        String times = sdr.format(new Date(i * 1000L));
        return times;

    }

    public static long getStringToDate(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
        return date.getTime();
    }

    // 获取当前时间
    public static String getNowDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
        return df.format(new Date());

    }

    // 获取星期
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    // String 转date
    public static Date stringToDate(String s) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sdf.parse(s);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;

    }

    // 时间加一减已
    public static String dateAR(Boolean is_add, String today) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date d;
            if (is_add) {
                d = new Date(f.parse(today).getTime() + 24 * 3600 * 1000);
            } else {
                d = new Date(f.parse(today).getTime() - 24 * 3600 * 1000);
            }

            return f.format(d);
        } catch (Exception ex) {
            return "输入格式错误";
        }

    }

    public static long time(String textString) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Long l = null;
        try {
            l = Long.valueOf(df.parse(textString).getTime() / 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return l;
    }


    public static String formatTime(long time) {
        String min = time / (1000 * 60) + "";
        String sec = time % (1000 * 60) + "";
        if (min.length() < 2) {
            min = "0" + time / (1000 * 60) + "";
        } else {
            min = time / (1000 * 60) + "";
        }
        if (sec.length() == 4) {
            sec = "0" + (time % (1000 * 60)) + "";
        } else if (sec.length() == 3) {
            sec = "00" + (time % (1000 * 60)) + "";
        } else if (sec.length() == 2) {
            sec = "000" + (time % (1000 * 60)) + "";
        } else if (sec.length() == 1) {
            sec = "0000" + (time % (1000 * 60)) + "";
        }
        return min + ":" + sec.trim().substring(0, 2);
    }

    /**
     * 比较两个时间相差天数
     */
    public static int calculateTimeGapDay(String time1, String time2) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                "yyyy-MM-dd");

        int day = 0;
        Date date1 = null;
        Date date2 = null;

        try {
            date1 = simpleDateFormat.parse(time1);
            date2 = simpleDateFormat.parse(time2);
            long millisecond = date2.getTime() - date1.getTime();
            day = (int) (millisecond / (24 * 60 * 60 * 1000));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return (day);
    }

    /*是否手机号*/
    public static boolean isChinaPhoneLegal(String str)
            throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

 
//    public static CharSequence matcherSearchText(int color, String string, String keyWord) {
//        if (string == null) string = "";
//        SpannableStringBuilder builder = new SpannableStringBuilder(string);
//
//        int indexOf = string.indexOf(keyWord);
//
//        if (indexOf != -1) {
//            builder.setSpan(new ForegroundColorSpan(UIUtils.getColor(color)), indexOf, indexOf + keyWord.length(), SPAN_EXCLUSIVE_EXCLUSIVE);
//
//        }
//
//        return builder;
//
//    }

//    public static CharSequence matcherSearchText(int color, String string, String keyWord) {
//        if (string == null) string = "";
//        SpannableStringBuilder builder = new SpannableStringBuilder(string);
//
//        int indexOf = string.indexOf(keyWord);
//
//        if (indexOf != -1) {
//            builder.setSpan(new ForegroundColorSpan(UIUtils.getColor(color)), indexOf, indexOf + keyWord.length(), SPAN_EXCLUSIVE_EXCLUSIVE);
//
//        }
//
//        return builder;
//
//    }

}
